package cn.kgc.tcst004.maoqichao.crowdfundingadminspringboot.controller;

import cn.kgc.tcst004.maoqichao.crowdfundingadminspringboot.common.ResultEntity;
import cn.kgc.tcst004.maoqichao.crowdfundingadminspringboot.pojo.Menu;
import cn.kgc.tcst004.maoqichao.crowdfundingadminspringboot.pojo.Tag;
import cn.kgc.tcst004.maoqichao.crowdfundingadminspringboot.service.TagService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/tag")
public class TagController {
    @Resource
    TagService tagService;

    @RequestMapping("/to/tag.html")
    public String selectTag(){
        return "tag-page";
    }

    @RequestMapping("/get/whole/tree")
    @ResponseBody
    public ResultEntity<Tag> getTree(){
        // 1.查询所有的树形节点用于组装
        List<Tag> tagList = tagService.getAll();
        // 2.将List<Tag>转换为Map<Tag的id,Tag>
        Map<Integer,Tag> tagMap = new HashMap<>();
        for (Tag tag : tagList) {
            tagMap.put(tag.getId(),tag);
        }
        // 3.声明变量用于存储根节点对象
        Tag rootNode = null;

        for (Tag tag : tagList) {
            //是父节点
            if (tag.getPid()==null){
                rootNode=tag;
                continue;
            }
            //是子节点从tagMap找到父节点，并添加到父节点的子节点集合中
            tagMap.get(tag.getPid()).getChildren().add(tag);
        }
        System.out.println(rootNode.toString());
        return ResultEntity.successWithoutData(rootNode);
    }
    @RequestMapping("/save")
    @ResponseBody
    public ResultEntity<String> saveMenu(Tag tag) {
        tagService.saveTag(tag);
        return ResultEntity.successWithoutData();
    }
    //回显数据
    @RequestMapping("/get/{tagId}")
    @ResponseBody
    public ResultEntity<Tag> getTagById(@PathVariable("tagId") Integer tagId) {
        Tag tag = tagService.getTagById(tagId);
        return ResultEntity.successWithoutData(tag);
    }
    @RequestMapping("/update")
    @ResponseBody
    public ResultEntity<String> update(Tag tag){
        tagService.update(tag);
        return ResultEntity.successWithoutData();
    }
    @RequestMapping("/tagRemove/{id}")
    @ResponseBody
    public ResultEntity<String> remove(@PathVariable("id") Integer id){
        tagService.tagRemove(id);
        return ResultEntity.successWithoutData();
    }
}
